package com.wy.supermarket.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wy.supermarket.entity.Detail;
import com.wy.supermarket.repository.DetailRepository;

@RestController
@RequestMapping("/detail")
public class DetailController {
	@Autowired //自动装载
	private DetailRepository detailRepository;
	
	@GetMapping("/findAll/{page}/{size}")
	public Page<Detail> findAll(@PathVariable("page") Integer page,@PathVariable("size") Integer size){
		Pageable pageable=PageRequest.of(page-1, size);
		return detailRepository.findAll(pageable);
	}
	
	@PostMapping("/addDetail")
	public String addDetail(@RequestBody Detail detail) {
		Detail result=detailRepository.save(detail);
		if(result!=null) {
			return "sucess";
		}else {
			return "error";
		}
	}
	
	@GetMapping("/findById/{dnum}")
	public Detail findById(@PathVariable("dnum") Integer dnum) {
		return detailRepository.findById(dnum).get();
	}
	
	@PutMapping("/updateDetail")
	public String updateDetail(@RequestBody Detail detail) {
		Detail result=detailRepository.save(detail);
		if(result!=null) {
			return "sucess";
		}else {
			return "error";
		}
	}
	
	@DeleteMapping("/deleteById/{dnum}")
	public Detail deleteById(@PathVariable("dnum") Integer dnum) {
		detailRepository.deleteById(dnum);
		return null;
	}

}
